class PlacesController < ApplicationController
  before_filter :login_required
  
  def new
    @page_title = I18n.t('place.new_title')
    @place = Place.new
    @place.build_location
    @place_photo = Photo.new  
    render :action => 'form'
  end
  
  def create
    @page_title = I18n.t('place.new_title')    
    @place = Place.new(:user => current_user)    
    @place.attributes = params[:place] if params[:place]
    @place.save if (success = @place && @place.valid?)
    if success && @place.errors.empty?
      if params[:ajax].to_s == "true"
        render :text => @place.id.to_s + "<br />" + @place.name
      else
        redirect_to "/" + @place.alias
      end      
    else     
      if params[:ajax].to_s == "true"
        render :inline => "<%= error_messages_for :place %>"  
      else
        @place_photo = Photo.new
         render :action => 'form'
      end      
    end
  end

  def edit    
    @page_title = I18n.t('place.edit_title')
    @place = Place.find(:first, :conditions => ["id = ?", params[:id]])    
    @place_photo = Photo.new  
    if @place.is_rewritable(current_user)
      render :action => 'form'
    else
      redirect_back_or_default('/')
    end
    
  end

  def update
    @page_title = I18n.t('place.edit_title')    
    @place = Place.find(:first, :conditions => ["id = ?", params[:id]])
    if @place and @place.is_rewritable(current_user)      
      @place.attributes = params[:place]    
      @place.save if (success = @place && @place.valid?)    
      if success && @place.errors.empty?
        redirect_to "/" + @place.alias
      else 
        @place_photo = Photo.new  
        render :action => 'form'
      end
    else
      redirect_to "/" + @place.alias
    end
  end
  
  def get_form
    new
  end
   
  def auto_complete_for_name
    places = ""    
    if params[:q].to_s != ""
      q = ""
      params[:q].split(" ").each { |i|  q += " name like \"%#{i.sub('"'," ")}%\" OR " }
      q = q[0, q.length - 4]
      names = Place.find(:all, :include => :location, 
                            :conditions => q, :limit => 20)
      names.each { |i| places += i.name + "|" + i.location.full_address + "|" + i.id.to_s + "|\n" }
    end
    places += "Clicca per aggiungere #{params[:q]} se non compare nella lista | |0|#{params[:q]}\n"
    
    render :text => places
  end
  
  def exist
    places = ""
    if params[:name].to_s != ""
      names = Place.find(:all, :include => :location, 
                            :conditions => ["name like ? ", "%" + params[:name] + "%"], :limit => 12)
      names.each { |i| places += "<a href='/#{i.alias}'>"+i.name + " " + i.location.full_address + " " + i.id.to_s + "</a><br />" }
    end
    render :text => places
  end
  
end
